from django.conf import settings
from django.shortcuts import render_to_response
from contifyuser.models import Member
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.template import RequestContext
from django.contrib.auth import logout
from django.contrib.auth import login
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect as redirect
from django.contrib.auth import authenticate
from contifyuser.forms import RegistrationFormConnectPeople
from StartGroup.models import Group
from groupMembers.models import Member_Group
import Constants
import connectpeople.Constants
import simplejson
from django.http import HttpResponse

# Home page view will add to it later 
def home(request):
    
    # Delete the group through ajax call
    if request.method == 'POST':
        # Get the comment id to be deleted
        gwebaddr = request.POST.__getitem__('gwebaddr')
            
        if gwebaddr:
            # Delete the event from database
            Group.objects.get(group_web_address=gwebaddr).delete()
            # Set response to success
            response = simplejson.dumps({'success':'success'})
    
    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
    
    user_group_list = []
    user_member_group_list = []
    render_template = Constants.contifyuser
    member = ''
    if connectpeople.Constants.session_userid in request.session:
        userid = request.session[connectpeople.Constants.session_userid]
        user_info = getUserInfo(userid)
        member = getMemberInfo(user_info)
        user_groups = getGroups(member)        
        user_group_list = getGroupsInList(user_groups)
        
        try:
            # Get the groups to which user is member
            mem_grp = Member_Group.objects.filter(user_id=userid)
            user_member_group_list = getGroupsInList(mem_grp)
        except Member_Group.DoesNotExist:
             print "I am not part of any group..."
             
        render_template += Constants.view_profile_template
    else:
        render_template += Constants.base_template
        
    return render_to_response(render_template, {connectpeople.Constants.signin_form_constant: AuthenticationForm(),
                            Constants.user_group_list_constant: user_group_list, Constants.profile_constant:member,
                            'user_member_group_list': user_member_group_list},
                            context_instance=RequestContext(request))


# Edit profile
def editprofile(request):
    render_template = Constants.contifyuser + Constants.base_template
    return render_to_response(render_template, {'form': AuthenticationForm()},
                            context_instance=RequestContext(request))
#    if request.method == 'POST':
#        connect_people_user = Member.objects.get(user=request.user)
#        
#        #if contify_user.role == 'PR':
#        #    contify_provider, created = Provider.objects.get_or_create(provider=contify_user)
#        #    provider_form = ProviderForm(data=request.POST)
#        #    if provider_form.is_valid():
#        #        if contify_provider is None:
#        #            cleanData = provider_form.clean()
#        #            created.provider_name = cleanData['provider_name']
#        #            created.address = cleanData['address']
#        #            created.save()
#        #            
#        #        else:
#        #            cleanData = provider_form.clean()
#        #            contify_provider.provider_name = cleanData['provider_name']
#        #            contify_provider.address = cleanData['address']
#        #            contify_provider.save()                   
#        #
#        #else:    
#        #    contify_buyer, created = Buyer.objects.get_or_create(buyer=contify_user)
#        #    buyer_form = BuyerForm(data=request.POST)
#        #    if buyer_form.is_valid():
#        #        if contify_buyer is None:
#        #            cleanData = buyer_form.clean()
#        #            created.buyer_name = cleanData['buyer_name']
#        #            created.address = cleanData['address']
#        #            created.save()
#        #            
#        #        else:
#        #            cleanData = buyer_form.clean()
#        #            contify_buyer.buyer_name = cleanData['buyer_name']
#        #            contify_buyer.address = cleanData['address']
#        #            contify_buyer.save()
#        return render_to_response('contifyuser/profile_update.html', context_instance=RequestContext(request))
#        
#    else:
#        connect_people_user = Member.objects.get(user=request.user)
#        
#        if contify_user.role == 'PR':
#            return render_to_response('contifyuser/contifyuser_form_buyer.html', {'form' : ProviderForm(), 'profile' : contify_user}, context_instance=RequestContext(request))
#            
#        else:    
#            return render_to_response('contifyuser/contifyuser_form_provider.html', {'form' : BuyerForm(), 'profile' : contify_user}, context_instance=RequestContext(request))
       
    
def viewprofile(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)        
        if user is not None:
            # Set a session value:
            request.session[connectpeople.Constants.session_userid] = username
            login(request, user)
            member = getMemberInfo(request.user)
            
            # Get the groups that user owns
            user_groups = getGroups(member)        
            user_group_list = getGroupsInList(user_groups)
            
            try:
                # Get the groups to which user is member
                mem_grp = Member_Group.objects.filter(user_id=username)
                user_member_group_list = getGroupsInList(mem_grp)
            except Member_Group.DoesNotExist:
                 print "I am not part of any group..."
            
            render_template = Constants.contifyuser + Constants.view_profile_template
            return render_to_response(render_template, {Constants.profile_constant:member,
                                    Constants.user_group_list_constant: user_group_list,
                                    'user_member_group_list': user_member_group_list},
                                      context_instance=RequestContext(request))
        else:
            render_template = Constants.contifyuser + Constants.login_template
            redirect('/connectpeople/auth/login')
            return render_to_response(render_template, {connectpeople.Constants.signin_form_constant: AuthenticationForm()},
                            context_instance=RequestContext(request))
            
def user_login(request):
    render_template = Constants.contifyuser + Constants.login_template
    return render_to_response(render_template, {connectpeople.Constants.signin_form_constant: AuthenticationForm()},
                            context_instance=RequestContext(request))
    
def logout_user(request):
    logout(request)
    response = redirect('/connectpeople/home/')
    return response    
    
    
# Helper function to obtain user info from User model
def getUserInfo(userid):
    return User.objects.get(username=userid)

# Helper function to obtain member info from Member model
def getMemberInfo(user_info):
    return Member.objects.get(user=user_info)
    
# Helper function to obtain Groups related to a member
def getGroups(member):
    return Group.objects.filter(member_user = member)
    
# Helper function to obtain Groups in a list format
def getGroupsInList(user_groups):
    user_group_list = []
    if user_groups is not None:
        for each in user_groups:
            user_group_list.append(each)
    
    return user_group_list